package com.enzo.prms.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.enzo.prms.common.session.RequestContext;
import com.enzo.prms.common.session.UserSessionInfo;

public class SecurityFilter implements Filter {

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		if (!req.getServletPath().equals("/jsp/login.jsp")
				&& !req.getServletPath().equals("/logout.action")
				&& !req.getServletPath().equals("/login.action")) {
			UserSessionInfo userSession = (UserSessionInfo) req.getSession().getAttribute("USI");
			if (userSession != null) {
				RequestContext.setUSI(userSession);
				chain.doFilter(request, response);
			} else {
				HttpServletResponse res = (HttpServletResponse) response;
				if ("XMLHttpRequest".equals(req.getHeader("X-Requested-With"))) {
					res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
				} else {
					res.sendRedirect("/jsp/login.jsp");
				}
			}
		}
	}

	@Override
	public void destroy() {

	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

}
